package com.chuanyang.driverh.mainmy;


import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.chuanyang.driverh.BaseApplication;
import com.chuanyang.driverh.R;
import com.chuanyang.driverh.base.BaseTitleActivity;
import com.chuanyang.driverh.responseresult.CarTeamDetailData;
import com.chuanyang.driverh.responseresult.CarTeamDetailResult;
import com.chuanyang.driverh.responseresult.CommentData;
import com.chuanyang.driverh.responseresult.CommentResult;
import com.chuanyang.driverh.responseresult.DriverInfoData;
import com.chuanyang.driverh.responseresult.Result;
import com.chuanyang.driverh.utils.ActivityUtil;
import com.chuanyang.driverh.utils.BitmapUtil;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

public class MyCarTeamHasActivity extends BaseTitleActivity {
    private MemberIconAdapter iconAdapter;
    private ArrayList<CarTeamDetailData.FleetDriverMsgListBean> members;
    private ArrayList<CarTeamDetailData.FleetLineListBean> lines;
    private RecyclerView recyclerView;
    // private ListView lv_carteam_comment;
    private HashMap params;
    private TextView tv_mycarteam_menmbermanage;
    private DriverInfoData driverinfo;
    private boolean isTeamLeader;
    private boolean isCarTeam;
    private ImageView iv_comment_icon1;
    private TextView tv_comment_name1;
    private TextView tv_comment_time1;
    private TextView tv_comment_content1;
    private ImageView iv_comment_icon2;
    private TextView tv_comment_name2;
    private TextView tv_comment_time12;
    private TextView tv_comment_content2;
    private LinearLayout ll_comment1_div;
    private LinearLayout ll_comment2_div;
    private ImageView iv_mycarteam_teamicon;
    private TextView tv_mycarteam_teamname;
    private TextView tv_mycarteam_role;
    private TextView tv_mycarteam_isleader;
    private TextView tv_mycarteam_leadername;
    private TextView tv_mycarteam_phone;
    private RatingBar rb_stars;
    private TextView tv_carteam_commentmore;
    private TextView tv_mycarteam_totalweight;
    private TextView tv_mycarteam_surplusweight;
    private TextView tv_mycarteam_daytotalcarnum;
    private TextView tv_mycarteam_surpluscarnum;
    private int ontraslatenum;
    private double captity;
    private double ontransweight;
    private TextView tv_lines_staadd;
    private TextView tv_lines_endadd;
    private ImageView iv_mycarteam_phone;
    private CarTeamDetailData carTeamDetailData;
    private TextView tv_mycarteam_oncount;
    private TextView tv_mycarteam_company;
    private LinearLayout ll_mycarteam_company;
    private View line_mycarteam_nocom;
    private String role;
    private TextView tv_mycarshipteam_souliang;
    private TextView tv_mycarshipteam_carship;
    private TextView tv_mycarshipteam_capweight;

    private Dialog dialog;
private LinearLayout ll_menmber;

    @Override
    protected int getContentResId() {
        return R.layout.my_act_maycarteamhas;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        showActivityLoading();
        //车队图片
        iv_mycarteam_teamicon = (ImageView) findViewById(R.id.iv_mycarteam_teamicon);
        //车队名称
        tv_mycarteam_teamname = (TextView) findViewById(R.id.tv_mycarteam_teamname);
        //显示是队长 还是队员
        tv_mycarteam_role = (TextView) findViewById(R.id.tv_mycarteam_role);
        //显示车队成员 还是船队成员
        tv_mycarteam_menmbermanage = (TextView) findViewById(R.id.tv_mycarteam_menmbermanage);
        //显示运力 还是吨位
        tv_mycarshipteam_capweight = (TextView) findViewById(R.id.tv_mycarshipteam_capweight);
        //显示车辆 还是船只
        tv_mycarshipteam_carship = (TextView) findViewById(R.id.tv_mycarshipteam_carship);
        //显示是辆 还是艘
        tv_mycarshipteam_souliang = (TextView) findViewById(R.id.tv_mycarshipteam_souliang);
        //是队长 这个影藏   队员时显示
        tv_mycarteam_isleader = (TextView) findViewById(R.id.tv_mycarteam_isleader);
        ll_mycarteam_company = (LinearLayout) findViewById(R.id.ll_mycarteam_company);
        tv_mycarteam_company = (TextView) findViewById(R.id.tv_mycarteam_company);
        //车队长名称
        tv_mycarteam_leadername = (TextView) findViewById(R.id.tv_mycarteam_leadername);
        //车队号码
        tv_mycarteam_phone = (TextView) findViewById(R.id.tv_mycarteam_phone);
        //拨打车队长电话
        iv_mycarteam_phone = (ImageView) findViewById(R.id.iv_mycarteam_phone);
        //总运力
        tv_mycarteam_totalweight = (TextView) findViewById(R.id.tv_mycarteam_totalweight);
        //剩余"2"吨 剩余吨位
        tv_mycarteam_surplusweight = (TextView) findViewById(R.id.tv_mycarteam_surplusweight);
        //总车辆数
        tv_mycarteam_daytotalcarnum = (TextView) findViewById(R.id.tv_mycarteam_daytotalcarnum);
        //空闲车辆数
        tv_mycarteam_surpluscarnum = (TextView) findViewById(R.id.tv_mycarteam_surpluscarnum);
        //在运车辆数
        tv_mycarteam_oncount = (TextView) findViewById(R.id.tv_mycarteam_oncount);
        //车队星级
        rb_stars = (RatingBar) findViewById(R.id.rb_stars);
        //查看更多评价
        tv_carteam_commentmore = (TextView) findViewById(R.id.tv_carteam_commentmore);
        recyclerView = (RecyclerView) findViewById(R.id.rv_mycarteam_icons);
        // lv_carteam_commonlines = (ListView) findViewById(R.id.lv_carteam_commonlines);
        iv_comment_icon1 = (ImageView) findViewById(R.id.iv_comment_icon1);
        tv_comment_name1 = (TextView) findViewById(R.id.tv_comment_name1);
        tv_comment_time1 = (TextView) findViewById(R.id.tv_comment_time1);
        tv_comment_content1 = (TextView) findViewById(R.id.tv_comment_content1);
        iv_comment_icon2 = (ImageView) findViewById(R.id.iv_comment_icon2);
        tv_comment_name2 = (TextView) findViewById(R.id.tv_comment_name2);
        tv_comment_time12 = (TextView) findViewById(R.id.tv_comment_time2);
        tv_comment_content2 = (TextView) findViewById(R.id.tv_comment_content2);
        ll_comment1_div = (LinearLayout) findViewById(R.id.ll_comment1_div);
        ll_comment2_div = (LinearLayout) findViewById(R.id.ll_comment2_div);
        tv_lines_staadd = (TextView) findViewById(R.id.tv_lines_staadd);
        tv_lines_endadd = (TextView) findViewById(R.id.tv_lines_endadd);
        ll_menmber = (LinearLayout) findViewById(R.id.ll_menmber);
//        lineadapter = new TeamDetailCommonLineAdapter(this, lines);
//        lv_carteam_commonlines.setAdapter(lineadapter);
        //找到展示成员图像的recycleview
        // recyclerView.setHasFixedSize(true);
    }

    @Override
    protected void initData() {
        driverinfo = BaseApplication.getInstance().getDriverInfo();
        setBackImg();
        lines = new ArrayList();
        members = new ArrayList();
        LinearLayoutManager manager = new LinearLayoutManager(MyCarTeamHasActivity.this);
        manager.setOrientation(OrientationHelper.HORIZONTAL);
        recyclerView.setLayoutManager(manager);
        iconAdapter = new MemberIconAdapter(members);
        recyclerView.setAdapter(iconAdapter);

        role = getIntent().getStringExtra("data");//"1"为车队，"2"船队
//        LogUtils.e("getFleetLeader", driverinfo.getFleet().getFleetLeader() + "-----" + driverinfo.getFleet());
        //此处判断司机是车队长还是成员
        if (driverinfo.getDriverId().equals(driverinfo.getFleet().getFleetLeader())) {
            //此时表示个人就是车队长)
            isTeamLeader = true;
            if (role.equals("1")) {
                getTitleTextView().setText("我的车队");
                isCarTeam=true;
            } else {
                getTitleTextView().setText("我的船队");
                isCarTeam=false;
            }
            getRightTextView().setText("重新编辑");
        }
        else {
            isTeamLeader = false;
            if (role.equals("1")) {
                isCarTeam=true;
                getRightTextView().setText("退出车队");
                getTitleTextView().setText("我的车队");
            } else {
                isCarTeam=false;
                getRightTextView().setText("退出船队");
                getTitleTextView().setText("我的船队");
            }
        }

        getComment();//获取车队评论
        getCarTeamDetailInfo();
    }

    @Override
    protected void initListener() {
        ll_menmber.setOnClickListener(this);
        tv_carteam_commentmore.setOnClickListener(this);
        iv_mycarteam_phone.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ll_menmber:
                if (driverinfo.getDriverId().equals(driverinfo.getFleet().getFleetLeader())) {
                    ActivityUtil.startActivity(activityContext,SettingMemberActivity.class);
                }else {
                    PrintUtil.toast(activityContext,"只有车队长有此权限");
                }
                break;
            case R.id.iv_mycarteam_phone:
                if (carTeamDetailData != null && carTeamDetailData.getUserPhone() != null) {
                    DialogUtil.dial(activityContext,carTeamDetailData.getUserPhone());
                }
                break;
            case R.id.tv_carteam_commentmore:
                Intent intent = new Intent(this, CommentActivity.class);
                intent.putExtra("fleetId", driverinfo.getFleet().getId() + "");
                intent.putExtra("driverId", "");
                startActivity(intent);
                break;
        }
    }

   /* private void dial(final String tel){
        dialog= DialogUtil.myDialog(activityContext, "拨打电话", "取消", "确定","确定拨打："+tel+"?", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.dialog_btn_left:
                        break;
                    case R.id.dialog_btn_right:
                        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + tel));
                        try {
                            if (PermissoinUtil.checkAndRequestPermission(activityContext, android.Manifest.permission.CALL_PHONE, "请给应用添加拨打电话的权限！"))
                            startActivity(intent);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                }
                dialog.cancel();
            }
        });
    }*/


    @Override
    protected void baseGoEnsure() {
        String  title="";
        String content="";
        if (isTeamLeader){
            title="解散";
            if (isCarTeam){
                content="您当前车队将会解散，是否解散车队？";
            }else{
                content="您当前船队将会解散，是否解散船队？";
            }
        }else{
            title="退出";
            if (isCarTeam){
                content="确定退出车队？";
            }else{
                content="确定退出船队？";
            }
        }
        dialog= DialogUtil.myDialog(activityContext, title, "取消", "确定", content, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                switch (v.getId()){
                    case R.id.dialog_btn_left:
                        break;
                    case R.id.dialog_btn_right:
                        if (isTeamLeader) {
                            deleteFleet(driverinfo.getFleet().getId() + "");
                        } else {
                            logoutCarTeam();
                        }
                        break;
                }
                dialog.cancel();
            }
        });
    }

    /**
     * 退出车队
     */
    private void logoutCarTeam() {
        DialogUtil.showLoadingDialog(activityContext,"退出车队...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("fleetId", driverinfo.getFleet().getId() + "");
        params.put("fleetDriverState", "3");
        params.put("driverId", driverinfo.getDriverId()+"");
        MyHttpUtil.updateFleetDriver(activityContext,params, new MyCallback<Result>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK ) {
                    PrintUtil.toast(activityContext,"您已退出车队");
                    BaseApplication.getInstance().getDriverInfoFromNet();
                    onBackPressed();
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });
    }

    /**
     * 车队长解散车队
     */
    private void deleteFleet(String fleedId) {
        DialogUtil.showLoadingDialog(activityContext,"解散车队");
        Map<String,String> params=new HashMap<String, String>();
        params.put("id", fleedId);
        MyHttpUtil.deleteFleet(activityContext,params, new MyCallback<Result>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK ) {
                    PrintUtil.toast(activityContext,"欢迎您下次创建车队");
                    //此时需要重新获取司机信息
                    BaseApplication.getInstance().getDriverInfoFromNet();
                    ActivityUtil.startActivity(activityContext,EditCarTeamActivity.class);
                    onBackPressed();
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });
    }

    private void getComment() {
        DialogUtil.showLoadingDialog(activityContext,null);
        Map<String,String> params=new HashMap<String, String>();
        params.put("page", "1");
        params.put("length", "2");
        params.put("fleetId", driverinfo.getFleet().getId() + "");
        MyHttpUtil.getByDriverOrFleet(activityContext,params, new MyCallback<CommentResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(CommentResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                        if (result.getData().getData() != null && result.getData().getData().size() > 0) {
                            CommentData.DataBean dataBean1 = result.getData().getData().get(0);
                            BitmapUtil.showImgForNetPath(dataBean1.getUserImage(),iv_comment_icon1);
    //                        YncApplication.getInstance().loadCircleImage(MyCarTeamHasActivity.this, dataBean1.getUserImage(), R.drawable.shengfeng, R.drawable.shengfeng, iv_comment_icon1);
                            tv_comment_name1.setText(dataBean1.getUserName() == null ? "匿名" : dataBean1.getUserName());
                            tv_comment_time1.setText(dataBean1.getCreateTime() == null ? "" : dataBean1.getCreateTime());
                            tv_comment_content1.setText(dataBean1.getEDetail() == null ? "" : dataBean1.getEDetail());
                            ll_comment1_div.setVisibility(View.VISIBLE);
                            if (result.getData().getData().size() >= 2) {
                                CommentData.DataBean dataBean2 = result.getData().getData().get(1);
                                BitmapUtil.showImgForNetPath(dataBean2.getUserImage(),iv_comment_icon2);
    //                            YncApplication.getInstance().loadCircleImage(MyCarTeamHasActivity.this, dataBean2.getUserImage(), R.drawable.shengfeng, R.drawable.shengfeng, iv_comment_icon2);
                                tv_comment_name2.setText(dataBean2.getUserName() == null ? "匿名" : dataBean2.getUserName());
                                tv_comment_time12.setText(dataBean2.getCreateTime() == null ? "" : dataBean2.getCreateTime());
                                tv_comment_content2.setText(dataBean2.getEDetail() == null ? "" : dataBean2.getEDetail());
                                ll_comment2_div.setVisibility(View.VISIBLE);
                            }

                        } else {
                            ll_comment1_div.setVisibility(View.GONE);
                            ll_comment2_div.setVisibility(View.GONE);
                        }
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }
                }
        });


    }

    private void getCarTeamDetailInfo() {
        DialogUtil.showLoadingDialog(activityContext,null);
        Map<String,String> params=new HashMap<String, String>();
        params.put("fleetId", driverinfo.getFleet().getId()+"");
        MyHttpUtil.selectFleetInfo(activityContext,params, new MyCallback<CarTeamDetailResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(CarTeamDetailResult result, int id) {
                if (result.getCode() == ConstUtil.OK  && result.getData() != null) {
                    carTeamDetailData = result.getData();
                    //获取在运车辆的相关信息
                    parseOnTraslateInfo(carTeamDetailData);
                    fillView(carTeamDetailData);
                    //如果存在车辆信息则显示该页面
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });

    }

    private void parseOnTraslateInfo(CarTeamDetailData data) {
        ontraslatenum = 0;
        ontransweight = 0;
        captity = data.getCapacity();
        for (CarTeamDetailData.FleetDriverMsgListBean bean : data.getFleetDriverMsgList()) {
            if (bean.getTransportState() != null && bean.getTransportState().equals("1"))//在运
            {
                ++ontraslatenum;
                ontransweight += bean.getCapacity();
            }
        }


    }


    private void fillView(CarTeamDetailData data) {
        hideActivityLoading();
        if (data.getFleetImgList().size() > 0) {
            BitmapUtil.showImgForNetPath(data.getFleetImgList().get(0).getImage(),iv_mycarteam_teamicon);
        }
        tv_mycarteam_teamname.setText(data.getFleetName());
        if (isTeamLeader) {
            tv_mycarteam_role.setText("队长");
            tv_mycarteam_isleader.setVisibility(View.GONE);
        } else {
            tv_mycarteam_role.setText("队员");
            tv_mycarteam_isleader.setVisibility(View.VISIBLE);
        }
        tv_mycarteam_leadername.setText(data.getUsername());
        tv_mycarteam_phone.setText(data.getUserPhone());
        if (!TextUtils.isEmpty(data.getLogisticsCompanyName())) {
            tv_mycarteam_company.setText(data.getLogisticsCompanyName());
        } else {
            ll_mycarteam_company.setVisibility(View.GONE);
        }
        if (data.getStar() != null) {
            rb_stars.setRating(data.getStar());
        }
        if (data.getFleetLineList() != null && data.getFleetLineList().size() > 0) {
            tv_lines_endadd.setText(data.getFleetLineList().get(0).getTargetCity());
            tv_lines_staadd.setText(data.getFleetLineList().get(0).getStartCity());
        }
        if(isCarTeam)
        {
            tv_mycarteam_daytotalcarnum.setText("共计" + data.getFleetDriverMsgList().size() + "辆");
            tv_mycarteam_menmbermanage.setText(" 车队成员");
            tv_mycarshipteam_carship.setText("车辆");
            tv_mycarshipteam_capweight.setText("运力");
            tv_mycarshipteam_souliang.setText("辆");
        }
        else {
            tv_mycarteam_daytotalcarnum.setText("共计" + data.getFleetDriverMsgList().size() + "艘");
            tv_mycarteam_menmbermanage.setText(" 船队成员");
            tv_mycarshipteam_carship.setText("船只");
            tv_mycarshipteam_capweight.setText("吨位");
            tv_mycarshipteam_souliang.setText("艘");
        }
        tv_mycarteam_surpluscarnum.setText((data.getFleetDriverMsgList().size() - ontraslatenum) + "");
        tv_mycarteam_oncount.setText(ontraslatenum + "");
        tv_mycarteam_surplusweight.setText((captity - ontransweight) + "");
        tv_mycarteam_totalweight.setText("共计" + captity + "吨");
        iconAdapter.setFleetDriverList((ArrayList<CarTeamDetailData.FleetDriverMsgListBean>) data.getFleetDriverMsgList());//设置成员的信息
    }







    class MemberIconAdapter extends RecyclerView.Adapter<MemberIconAdapter.MyViewHolder> {


        private ArrayList<CarTeamDetailData.FleetDriverMsgListBean> fleetDriverList;
        private MyViewHolder holder;

        public void setFleetDriverList(ArrayList<CarTeamDetailData.FleetDriverMsgListBean> fleetDriverList) {
            this.fleetDriverList = fleetDriverList;
            notifyDataSetChanged();
        }

        public MemberIconAdapter(ArrayList<CarTeamDetailData.FleetDriverMsgListBean> fleetDriverList) {
            this.fleetDriverList = fleetDriverList;
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            // 给ViewHolder设置布局文件
            holder = new MyViewHolder(View.inflate(MyCarTeamHasActivity.this, R.layout.my_item_carteammenmber, null));
            return holder;
        }


        @Override
        public void onBindViewHolder(MyViewHolder holder, final int position) {
            CarTeamDetailData.FleetDriverMsgListBean bean = fleetDriverList.get(position);
            holder.name.setText(bean.getUsername());
            holder.weight.setText(bean.getCapacity() + "t");
            if (bean.getTransportState() != null && bean.getTransportState().equals("1")) {
                holder.iv_menmberstate.setSelected(true);

            }
            else {
                holder.iv_menmberstate.setSelected(false);
            }
            BitmapUtil.showImgForNetPath(bean.getUserImage(),holder.peopleicon);
//            YncApplication.getInstance().loadCircleImage(MyCarTeamHasActivity.this, bean.getUserImage(), R.drawable.shengfeng, R.drawable.shengfeng, holder.peopleicon);
            holder.ll_cartean_div.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent(MyCarTeamHasActivity.this,DriverInfoActivity.class);
                    intent.putExtra("isCarTeamMenmber",isCarTeam);
                    intent.putExtra("driverId", fleetDriverList.get(position).getDriverId() + "");
                    startActivity(intent);

                }
            });

        }

        @Override
        public int getItemCount() {
            return fleetDriverList.size();
        }

        // 重写的自定义ViewHolder
        class MyViewHolder extends RecyclerView.ViewHolder {
            public ImageView peopleicon;
            public ImageView iv_menmberstate;
            public TextView name;
            public TextView weight;
            public LinearLayout ll_cartean_div;

            public MyViewHolder(View v) {
                super(v);
                name = (TextView) v.findViewById(R.id.tv_menmbername);
                weight = (TextView) v.findViewById(R.id.tv_menmverweight);
                peopleicon = (ImageView) v.findViewById(R.id.iv_menmbericon);
                iv_menmberstate = (ImageView) v.findViewById(R.id.iv_menmberstate);
                ll_cartean_div = (LinearLayout) v.findViewById(R.id.ll_cartean_div);
            }
        }

    }
    ;

}

